package com.woniuxy.microsystemsarserver.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.woniuxy.microsystemsarserver.bean.ConstantPropertiesUtils;
import com.woniuxy.microsystemsarserver.service.IOssService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
@Service
public class OssServiceImpl implements IOssService {
    /**
     * 上传文件的具体业务
     * @param file
     * @return
     */
    @Override
    public String uploadFile(MultipartFile file) {

        //得到文件的真实名称
        String filename = file.getOriginalFilename();

        filename  =  UUID.randomUUID().toString() + filename;

        String endpoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;

        // 上传文件流。
        try {
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            InputStream inputStream = file.getInputStream();
            ossClient.putObject(bucketName, filename, inputStream);
            String url = "https://" + bucketName + "." + endpoint + "/" + filename;

            // 关闭OSSClient。
            ossClient.shutdown();

            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
